<?php
class ControllerLogin extends Controller {
	public function __construct($q) {
		parent::__construct($q);
	}
	
	public function execute() {
		$v = $this->getQuery();
		$w = $this->getQuery();

		if(empty($v) || empty($w))
			return $this->doHelp();

		$this->doLogin($v, $w);
	}
	
	private function doHelp() {
		View::show("Usage : login nick password");
	}
	
	private function doLogin($v, $w) {
		View::show("[+] Connecting to remote server: ", false);
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, "https://clients.1and1.fr/xml/config/Login");
		curl_setopt($ch, CURLOPT_AUTOREFERER, true);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($ch, CURLOPT_COOKIEJAR, ModelConfig::get('cookie'));
		curl_setopt($ch, CURLOPT_COOKIEFILE, ModelConfig::get('cookie'));
		$init = curl_exec($ch);

		preg_match('/jsessionid=([a-zA-Z0-9\.]+)/', $init, $m);
		preg_match('/__SBMT:([A-Za-z0-9]+)/', $init, $n);

		if(isset($m[1]) && isset($n[1])) {
			ModelConfig::set('sessionid', $m[1]);
			$input = $n[1];
			View::show("done");
		} else
			return View::show("failed");
		
		View::show("[+] Loggin in: ", false);
		curl_setopt($ch, CURLOPT_URL,
				"https://clients.1and1.fr/xml/config/Login;jsessionid=".ModelConfig::get('sessionid'));
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, array(
				'__lf'					=>	'HomeFlow',
				'__sendingdata'			=>	'1',
				'__sendingauthdata'		=>	'1',
				'login.SelectContract'	=>	'',
				'login.User'			=>	$v,
				'login.Pass'			=>	$w,
				$input.'::'				=>	'',
				$input.':.x:'			=>	'41',
				$input.':.y:'			=>	'13',
				));
		$login = curl_exec($ch);
		
		if(strpos($login, "Dashboard") === false)
			View::show('failed');
		else {
			ModelUser::newInstance(array(
					'nick'	=> $v,
					'pass'	=> '',
					'host'	=> '1and1.fr'));
			View::show('done');
		}
		curl_close($ch);
	}
}